package com.server;

import lombok.extern.slf4j.Slf4j;


import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**********************************
 * @author wmx
 * @date 2019/8/26 11:13
 * @description:
 * @version 1.0
 * OIO中，每个线程只能处理一个channel（同步的，该线程和该channel绑定，）。
 * NIO中，每个线程可以处理多个channel（异步）。
 ************************************/
@Slf4j
public class OIOServer {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(10001);
         log.info("【服务器已经启动】");
         while (true){
             Socket socket = serverSocket.accept();
             log.info("【新来了一个客服端】");
             executorService.execute(()->{
                 handle(socket);
             });

         }
    }

    //处理业务数据
    public static void handle(Socket socket){
        try {
            byte [] bytes = new byte[1024];
            InputStream stream =  socket.getInputStream();
            while (true){
                int read = stream.read(bytes);
                if(read !=-1){
                    log.info(new String(bytes,0,read));
                }else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
